package org.jeecg.modules.sxaq.bigscreen.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.sxaq.anr.entity.RecordAbnormal;
import org.jeecg.modules.sxaq.anr.service.IRecordAbnormalService;
import org.jeecg.modules.sxaq.ior.entity.RecordInout;
import org.jeecg.modules.sxaq.ior.service.IRecordInoutService;
import org.jeecg.modules.sxaq.utils.Urls;
import org.jeecg.modules.system.service.ISysUserDeviceService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 大屏
 * @Author: DHC
 * @Date:  2020-12-01
 */
@Api(tags="大屏相关")
@RestController
@RequestMapping("/sys/bigScreen")
@Slf4j
public class BigScreenController {

    @Autowired
    private IRecordInoutService recordInoutService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserDeviceService sysUserDeviceService;
    @Autowired
    private IRecordAbnormalService recordAbnormalService;

    @Value("${sxaq.factoryCode}")
    private String factoryCode;

    @Value("${sxaq.cloudUrl}")
    private String cloudUrl;

    @AutoLog(value = "进场人数")
    @ApiOperation(value="进场人数", notes="进场人数")
    @GetMapping(value = "/getApproachPeoples")
    public Result<?> getApproachPeoples(@RequestParam(name="startTime") String startTimeStr,
                                        @RequestParam(name="endTime") String endTimeStr) throws ParseException {

        return getInoutData(startTimeStr,endTimeStr,1);
    }

    @AutoLog(value = "出场人数")
    @ApiOperation(value="出场人数", notes="出场人数")
    @GetMapping(value = "/getShowUpPeoples")
    public Result<?> getShowUpPeoples(@RequestParam(name="startTime") String startTimeStr,
                                      @RequestParam(name="endTime") String endTimeStr) {

        return getInoutData(startTimeStr,endTimeStr,2);
    }

    // 获取进出场事件
    private Result<?> getInoutData(String startTimeStr, String endTimeStr, int type) {

        if (startTimeStr==null || startTimeStr.isEmpty()) {
            return Result.error("开始时间不正确！");
        }

        if (endTimeStr==null || endTimeStr.isEmpty()) {
            return Result.error("结束时间不正确！");
        }

//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.between("create_time",startTimeStr, endTimeStr);
//        queryWrapper.eq("type",type);
//        queryWrapper.orderByDesc("create_time");
//
//        List<RecordInout> results = recordInoutService.list(queryWrapper);
//
//        // 分组
//        Map<String,List<RecordInout>> result = new HashMap<>();
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        for(RecordInout recordInout : results){
//            String date = df.format(recordInout.getCreateTime());
//            List<RecordInout> tempList = result.get(date);
//            if(tempList == null){
//                tempList = new ArrayList();
//                tempList.add(recordInout);
//
//                result.put(date,tempList);
//            }else{
//                tempList.add(recordInout);
//            }
//        }

//        Map<String, Integer> newResult = new HashMap<>();
//        for (Map.Entry<String, List<RecordInout>> entry : result.entrySet()) {
//            newResult.put(entry.getKey(), entry.getValue().size());
//        }

        List<HashMap<String, String>> ret =  recordInoutService.getInoutCount(startTimeStr, endTimeStr, type);
        Map<String, Integer> newResult = new HashMap<>();
        for (int i=0; i<ret.size(); i++) {
            newResult.put(ret.get(i).get("event_time"), Integer.parseInt(String.valueOf(ret.get(i).get("ct"))));
        }

        return Result.ok(newResult);
    }

    @AutoLog(value = "场内/场外人数")
    @ApiOperation(value="场内/场外人数", notes="场内/场外人数")
    @GetMapping(value = "/getEventPeoples")
    public Result<?> getNormalPeoples() {
        try {
            Result inCount = getEventData(1);
            Result outCount = getEventData(2);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("inCount",inCount.getResult());
            jsonObject.put("outCount",outCount.getResult());
            return Result.ok(jsonObject);
        } catch (Exception e) {
            return Result.error("操作失败");
        }
    }

    // 获取上报事件
    private Result<?> getEventData(int type) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", "0");
        if (type==1) {
            queryWrapper.eq("event_type",1);
        } else  {
            queryWrapper.ne("event_type",1);
        }
        queryWrapper.orderByDesc("create_time");
        int result = sysUserService.count(queryWrapper);
        return Result.ok(result);
    }

    @AutoLog(value = "安全事件")
    @ApiOperation(value="安全事件", notes="安全事件")
    @GetMapping(value = "/getAllEvents")
    public Result<?> getAllEvents(@RequestParam(name="startTime") String startTimeStr,
                                  @RequestParam(name="endTime") String endTimeStr) {

        if (startTimeStr==null || startTimeStr.isEmpty()) {
            return Result.error("开始时间不正确！");
        }

        if (endTimeStr==null || endTimeStr.isEmpty()) {
            return Result.error("结束时间不正确！");
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time",startTimeStr, endTimeStr);
        queryWrapper.ne("type",200);
        queryWrapper.orderByDesc("create_time");

        List<RecordAbnormal> results = recordAbnormalService.list(queryWrapper);

        return Result.ok(results);
    }

    @AutoLog(value = "大屏基本信息")
    @ApiOperation(value="大屏基本信息", notes="大屏基本信息")
    @GetMapping(value = "/getBaseInfo")
    public Result<?> getBaseInfo() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("factoryCode", factoryCode);

            // 授权数据
            int authWorkCount = 0; // 终端授权数-已注册用户数
            int authLeftCount = 0; // 剩余授权数-允许最大用户数减已注册用户数
            String authLeftDay = "0"; // 授权剩余天数
            // 设备数据
            int deviceOnlineCount = 0; // 设备在线-进场设备数
            int deviceActiveCount = 0; // 已激活用户数-已注册设备数
            int deviceInActiveCount = 0; // 未激活用户数-暂时0
            // 平台数据
            int platformAndroid = 0; // android平台数
            int platformIos = 0; // ios平台数
            int platformWin = 0; // win平台数
            // 用户
            int userTotal = 0; // 已注册用户数
            int userActive = 0; // 已激活用户数，不包括垃圾箱中用户和冻结用户

            // 已注册用户数
            authWorkCount = sysUserService.getUserCount();

            // 设备总数
            deviceOnlineCount = sysUserDeviceService.getDeviceInCount();
            deviceActiveCount = sysUserDeviceService.getDeviceCount();

            // 平台数据
            platformAndroid = sysUserDeviceService.getDeviceAndroidCount();
            platformIos = sysUserDeviceService.getDeviceIosCount();
            platformWin = deviceActiveCount - platformAndroid - platformIos;

            // 用户数据
            userTotal = authWorkCount;
            userActive = sysUserService.getUserValidCount();

            // 从云端取数据
            JSONObject json = doPost(cloudUrl + Urls.AUTH_INFO, jsonObject);
            if (json != null) {
                boolean success = json.getBoolean("success");
                if (success) {
                    JSONObject result = (JSONObject)json.get("result");
                    authLeftDay = result.getString("authLeftDay");
                    authLeftCount = Integer.parseInt(result.getString("workMaxCount")) -  authWorkCount;
                } else {
                    return Result.error("操作失败");
                }
            } else {
                return Result.error("操作失败");
            }

            JSONObject ret = new JSONObject();
            ret.put("authLeftCount", authLeftCount);
            ret.put("authLeftDay", authLeftDay);
            ret.put("authWorkCount", authWorkCount);
            ret.put("deviceOnlineCount", deviceOnlineCount);
            ret.put("deviceActiveCount", deviceActiveCount);
            ret.put("deviceInActiveCount", deviceInActiveCount);
            ret.put("platformAndroid", platformAndroid);
            ret.put("platformIos", platformIos);
            ret.put("platformWin", platformWin);
            ret.put("userTotal", userTotal);
            ret.put("userActive", userActive);
            return Result.ok(ret);
        } catch (Exception e) {
            return Result.error("操作失败");
        }
    }

    private JSONObject doPost(String url, JSONObject data) {
        HttpClient client = HttpClients.createDefault();

        // 要调用的接口方法
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            post.setEntity(new StringEntity(data.toString(), Charset.forName("UTF-8")));
            post.addHeader("content-type", "application/json");
            post.setHeader("Accept", "application/json");
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            jsonObject = JSONObject.parseObject(response1);
            System.out.println(response1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject;
    }
}

